package cn.zmall.manager.service.impl;

import cn.zmall.common.exception.ZmallException;
import cn.zmall.common.pojo.DataTablesResult;
import cn.zmall.manager.dto.DtoUtil;
import cn.zmall.manager.dto.MemberDto;
import cn.zmall.manager.mapper.TbMemberMapper;
import cn.zmall.manager.pojo.TbMember;
import cn.zmall.manager.pojo.TbMemberExample;
import cn.zmall.manager.service.MemberService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

/**
 * @Author BinBini
 * @Date 2020/11/18 11:03
 * @Version 1.0
 */
@Service
public class MemberServiceImpl implements MemberService {

    private final static Logger log = LoggerFactory.getLogger(MemberService.class);

    @Autowired
    private TbMemberMapper tbMemberMapper;

    @Override
    public TbMember getMemberById(Long id) {
        TbMember tbMember;
        try{
            tbMember = tbMemberMapper.selectByPrimaryKey(id);
        }catch (Exception e) {
            throw new ZmallException("ID获取会员信息失败");
        }
        tbMember.setPassword("");
        return tbMember;
    }

    @Override
    public DataTablesResult getMemberList(int draw, int start, int length, String search, String minDate, String maxDate, String orderCol, String orderDir) {
        DataTablesResult result = new DataTablesResult();

        PageHelper.startPage(start/length + 1, length);
        List<TbMember> list = tbMemberMapper.selectByMemberInfo("%"+search+"%", minDate, maxDate, orderCol, orderDir);
        PageInfo<TbMember> pageInfo = new PageInfo<>(list);

        for(TbMember tbMember : list) {
            tbMember.setPassword("");
        }

        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setRecordsTotal(getMemberCount().getRecordsTotal());

        result.setDraw(draw);
        result.setData(list);
        return result;
    }

    @Override
    public DataTablesResult getRemoveMemberList(int draw, int start, int length, String search, String minDate, String maxDate, String orderCol, String orderDir) {
        DataTablesResult result = new DataTablesResult();

        PageHelper.startPage(start/length + 1, length);
        List<TbMember> list = tbMemberMapper.selectByRemoveMemberInfo("%"+search+"%", minDate, maxDate, orderCol, orderDir);
        PageInfo<TbMember> pageInfo = new PageInfo<>(list);

        for(TbMember tbMember : list) {
            tbMember.setPassword("");
        }

        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setRecordsTotal(getRemoveMemberCount().getRecordsTotal());

        result.setDraw(draw);
        result.setData(list);
        return result;
    }

    @Override
    public DataTablesResult getMemberCount() {
        DataTablesResult result = new DataTablesResult();
        TbMemberExample example = new TbMemberExample();
        TbMemberExample.Criteria criteria = example.createCriteria();
        criteria.andStateNotEqualTo(2);
        try {
            result.setRecordsTotal((int)tbMemberMapper.countByExample(example));
        }catch (Exception e){
            throw new ZmallException("统计会员数失败");
        }
        return result;
    }

    @Override
    public DataTablesResult getRemoveMemberCount() {
        DataTablesResult result = new DataTablesResult();
        TbMemberExample example = new TbMemberExample();
        TbMemberExample.Criteria criteria = example.createCriteria();
        criteria.andStateEqualTo(2);
        try {
            result.setRecordsTotal((int)tbMemberMapper.countByExample(example));
        }catch (Exception e) {
            throw new ZmallException("统计移除会员总数失败");
        }
        return result;
    }

    @Override
    public TbMember getMemberByPhone(String phone) {
        List<TbMember> list;
        TbMemberExample example = new TbMemberExample();
        TbMemberExample.Criteria criteria = example.createCriteria();
        criteria.andPhoneEqualTo(phone);
        try {
            list = tbMemberMapper.selectByExample(example);
        }catch (Exception e) {
            throw new ZmallException("根据手机号获取会员失败");
        }
        if(!list.isEmpty()) {
            list.get(0).setPassword("");
            return list.get(0);
        }
        return null;
    }

    @Override
    public TbMember getMemberByEmail(String email) {
        List<TbMember> list;
        TbMemberExample example = new TbMemberExample();
        TbMemberExample.Criteria criteria = example.createCriteria();
        criteria.andEmailEqualTo(email);
        try {
            list = tbMemberMapper.selectByExample(example);
        }catch (Exception e) {
            throw new ZmallException("根据邮箱获取会员失败");
        }
        if(!list.isEmpty()) {
            list.get(0).setPassword("");
            return list.get(0);
        }
        return null;
    }

    @Override
    public TbMember getMemberByUsername(String username) {
        List<TbMember> list;
        TbMemberExample example = new TbMemberExample();
        TbMemberExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(username);
        try {
            list = tbMemberMapper.selectByExample(example);
        }catch (Exception e) {
            throw new ZmallException("根据用户名获取会员失败");
        }
        if(!list.isEmpty()) {
            list.get(0).setPassword("");
            return list.get(0);
        }
        return null;
    }

    @Override
    public TbMember addMember(MemberDto memberDto) {
        TbMember tbMember = DtoUtil.MemberDtoToTbMember(memberDto);
        if(getMemberByPhone(tbMember.getPhone()) != null) {
            throw new ZmallException("手机号已被注册");
        }
        if(getMemberByEmail(tbMember.getEmail()) != null) {
            throw new ZmallException("邮箱已被注册");
        }
        if(getMemberByUsername(tbMember.getUsername()) != null) {
            throw new ZmallException("用户名已被注册");
        }

        tbMember.setState(1);
        tbMember.setCreated(new Date());
        tbMember.setUpdated(new Date());
        String md5Pass = DigestUtils.md5DigestAsHex(tbMember.getPassword().getBytes());
        tbMember.setPassword(md5Pass);
        if(tbMemberMapper.insert(tbMember) != 1) {
            throw new ZmallException("用户添加失败");
        }
        return getMemberByPhone(tbMember.getPhone());
    }

    @Override
    public TbMember updateMember(Long id, MemberDto memberDto) {
        TbMember tbMember = DtoUtil.MemberDtoToTbMember(memberDto);
        tbMember.setId(id);
        tbMember.setUpdated(new Date());
        TbMember oldMember=getMemberById(id);
        tbMember.setState(oldMember.getState());
        tbMember.setCreated(oldMember.getCreated());
        if(tbMember.getPassword()==null||tbMember.getPassword()==""){
            tbMember.setPassword(oldMember.getPassword());
        }else{
            String md5Pass = DigestUtils.md5DigestAsHex(tbMember.getPassword().getBytes());
            tbMember.setPassword(md5Pass);
        }

        if (tbMemberMapper.updateByPrimaryKey(tbMember) != 1){
            throw new ZmallException("更新会员信息失败");
        }
        return getMemberById(id);
    }

    @Override
    public TbMember changeMemberPassword(Long id, MemberDto memberDto) {
        TbMember tbMember = tbMemberMapper.selectByPrimaryKey(id);

        String md5Pass = DigestUtils.md5DigestAsHex(memberDto.getPassword().getBytes());
        tbMember.setPassword(md5Pass);
        tbMember.setUpdated(new Date());

        if(tbMemberMapper.updateByPrimaryKey(tbMember) != 1) {
            throw new ZmallException("修改会员密码失败");
        }
        return getMemberById(id);
    }

    @Override
    public TbMember alertMemberState(Long id, Integer state) {
        TbMember tbMember = tbMemberMapper.selectByPrimaryKey(id);
        tbMember.setState(state);
        tbMember.setUpdated(new Date());

        if(tbMemberMapper.updateByPrimaryKey(tbMember) != 1) {
            throw new ZmallException("更新会员状态失败");
        }
        return getMemberById(id);
    }

    @Override
    public int deleteMember(Long id) {
        if(tbMemberMapper.deleteByPrimaryKey(id) != 1) {
            throw new ZmallException("彻底删除会员失败");
        }
        return 1;
    }

    @Override
    public TbMember getMemberByEditPhone(Long id, String phone) {
        TbMember tbMember = getMemberById(id);
        TbMember newTbMember = null;

        if(tbMember.getPhone() == null || !tbMember.getPhone().equals(phone)) {
            newTbMember = getMemberByPhone(phone);
            newTbMember.setPassword("");
        }
        return newTbMember;
    }

    @Override
    public TbMember getMemberByEditEmail(Long id, String email) {
        TbMember tbMember = getMemberById(id);
        TbMember newTbMember = null;

        if(tbMember.getEmail() == null || !tbMember.getEmail().equals(email)) {
            newTbMember = getMemberByEmail(email);
            newTbMember.setPassword("");
        }
        return newTbMember;
    }

    @Override
    public TbMember getMemberByEditUsername(Long id, String username) {
        TbMember tbMember = getMemberById(id);
        TbMember newTbMember = null;

        if(tbMember.getUsername() == null || !tbMember.getUsername().equals(username)) {
            newTbMember = getMemberByUsername(username);
            newTbMember.setPassword("");
        }
        return newTbMember;
    }
}
